<?php

require_once 'Pipes/Exception.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Storage.php';

class Pipes_Storage implements PipesImpl_Storage
{
    private $_pdo = null;
    
    public function __construct(PipesImpl_Config $config)
    {
        $this->_pdo = $config->pdo;
    }
    
    public function getRecord($name, PipesImpl_Filter $criteria)
    {
        $name = strtolower($name);
        $sql = "SELECT * FROM {$name}s WHERE {$criteria->getCondition()}";
        $statement = $this->_pdo->prepare($sql);
        if ($statement === false || $statement->execute($criteria->getSubstitutions()) === false) {
            throw new Pipes_Exception('Problem preparing statement [' . $sql . ']');
        }
        
        $return = $statement->fetch(PDO::FETCH_ASSOC);
        $statement->closeCursor();
        return $return;
    }
    
    public function getRecords($name)
    {
        $name = strtolower($name);
        $sql = "SELECT * FROM {$name}s";
        $statement = $this->_pdo->query($sql);
        if ($statement === false) {
            throw new Pipes_Exception('Problem executing query [' . $sql . ']');
        }
        
        $return = $statement->fetchAll(PDO::FETCH_ASSOC);
        $statement->closeCursor();
        return $return;
    }
    
    public function add($name, array $properties)
    {
        $columns = array_keys($properties);
        $valueHolders =  array();
        foreach ($columns as $column) {
            $valueHolders[] = ":{$column}";
        }
        
        $columnsSql = implode('`, `', $columns);
        $valueHoldersSql = implode(', ', $valueHolders);
        $sql = "INSERT INTO {$name}s (`{$columnsSql}`) VALUES ({$valueHoldersSql})";
        
        $statement = $this->_pdo->prepare($sql);
        $statement->execute($properties);
    }
    
    public function modify($name, array $properties)
    {
        $idColumn = "{$name}_id";
        
        $updates = array();
        foreach ($properties as $key => $value) {
            if ($key == $idColumn) {
                continue;
            }
            $updates[] = "`{$key}` = :{$key}";
        }
        
        $updatesSql = implode(', ', $updates);
        $sql = "UPDATE {$name}s SET {$updatesSql} WHERE `{$idColumn}` = :{$idColumn}";
        
        $statement = $this->_pdo->prepare($sql);
        $statement->execute($properties);
    }

    public function remove($name, $id) {
        $idColumn = "{$name}_id";
        $sql = "DELETE FROM {$name}s WHERE `{$idColumn}` = ?";
        
        $statement = $this->_pdo->prepare($sql);
        $statement->execute(array($id));
    }
}

